package com.cloudkinto.service.freemarkdertemplate.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.freemarkdertemplate.FreeMarkerTemplateService;
import com.cloudkinto.service.freemarkdertemplate.vo.FreeMarkerTemplateDeleteRulesReq;
import com.cloudkinto.service.freemarkdertemplate.vo.FreeMarkerTemplateReq;
import com.cloudkinto.service.freemarkdertemplate.vo.FreeMarkerTemplateRulesReq;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FreeMarkerTemplateServiceImpl  extends ServiceImpl<FreeMarkerTemplateDao, FreeMarkerTemplateDo> implements FreeMarkerTemplateService {

    @Autowired
    private FreeMarkerTemplateRulesDao freeMarkerTemplateRulesDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private TemplatesDao templatesDao;
    @Autowired
    private TemplateRuleRelationsDao templateRuleRelationsDao;
   @Autowired
    private FreeMarkerTemplatePlaceHolderDao freeMarkerTemplatePlaceHolderDao;
   @Autowired
   private TemplatesContentDao templatesContentDao;
    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FreeMarkerTemplateDo> wrapper = queryBuild(map);
        IPage<FreeMarkerTemplateDo> page = pageInit(map);
        page = this.page(page, wrapper);
//        List<FirstVesselOrderPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
//        result.setMapInfo(census(map));
        return result;
    }

    @Override
    public FreeMarkerTemplateDo detail(Long id) {
        LambdaQueryWrapper<FreeMarkerTemplateDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FreeMarkerTemplateDo::getId, id);
        return this.getOne(wrapper);
    }

    @Override
    public FreeMarkerTemplateDo delete(Long id) {
        // 获取要删除的记录
        FreeMarkerTemplateDo one = this.getById(id);
        if (one == null) {
            throw new IllegalArgumentException("FreeMarkerTemplate not found with ID: " + id);
        }

        // 删除记录
        this.removeById(id);

        return one;
    }


    @Override
    @Transactional
    public void add(FreeMarkerTemplateReq req, Long userId) {
        UserDo user = userDao.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("User not found with ID: " + userId);
        }

        long currentTimeMillis = System.currentTimeMillis();
        req.setTimesStamp(currentTimeMillis);

        String userName = user.getUserName();
        FreeMarkerTemplateDo entityDo = new FreeMarkerTemplateDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCreatedBy(userName);
        if (req.getId() != null) {

            // 设置ID以确保更新操作
            entityDo.setId(req.getId());
        }

        boolean result = saveOrUpdate(entityDo);
        if (result) {
            // 将生成的ID设置回req对象
            req.setId(entityDo.getId());
            saveTemplatesContent(req);
        }
    }

    private void saveTemplatesContent(FreeMarkerTemplateReq req) {
        Long id = req.getId();
        TemplatesDo templatesDo = templatesDao.selectById(id);
        TemplatesContentDo templatesContentDo=new TemplatesContentDo();
        templatesContentDo.setContent(templatesDo.getContent());
        templatesContentDo.setTemplateId(Math.toIntExact(id));
        templatesContentDo.setUrl(templatesDo.getUrl());
        templatesContentDo.setCreatedBy(templatesDo.getCreatedBy());
        templatesContentDo.setTimeStamp(req.getTimesStamp());
        templatesContentDo.setMailTitle(templatesDo.getMailTitle());
        templatesContentDo.setUpdatedAt(templatesDo.getUpdatedAt());
        templatesContentDao.insert(templatesContentDo);
    }


    @Override
    public List<FreeMarkerTemplateRulesDo> rulesList(Long id) {
        LambdaQueryWrapper<TemplateRuleRelationsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRuleRelationsDo::getTemplateId, id);
        List<Long> ruleIds = templateRuleRelationsDao.selectList(wrapper).stream()
                .map(TemplateRuleRelationsDo::getRuleId)
                .collect(Collectors.toList());

        if (ruleIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 批量查询规则列表
        List<FreeMarkerTemplateRulesDo> ruleList = freeMarkerTemplateRulesDao.selectBatchIds(ruleIds);
        return ruleList;
    }

    @Override
    @Transactional
    public Map<String,Object> addRules(FreeMarkerTemplateRulesReq req, Long userId) {
        UserDo userDo = userDao.selectById(userId);
        String userName = userDo.getUserName();
        Long templateId = req.getTemplateId();

        FreeMarkerTemplateRulesDo dto = new FreeMarkerTemplateRulesDo();
        BeanUtils.copyProperties(req, dto);

        // 获取当前时间并格式化
        String formattedDateTime = getCurrentFormattedDateTime();
        dto.setCreatedAt(formattedDateTime);
        dto.setUpdatedAt(formattedDateTime);
        dto.setCreatedBy(userName);
        //插入之前进行数据校验
        Long resultId = handlerRules(req, userId);
        if(resultId==0L){
            // 插入规则
            freeMarkerTemplateRulesDao.insert(dto);
        }
        Map map=new HashMap();
        // 检查该规则是否已经关联到指定的模板
        TemplateRuleRelationsDo templateRuleRelationsDo = templateRuleRelationsDao.selectOne(
                new LambdaQueryWrapper<TemplateRuleRelationsDo>()
                        .eq(TemplateRuleRelationsDo::getRuleId, resultId)
                        .eq(TemplateRuleRelationsDo::getTemplateId, req.getTemplateId())
        );

        if (templateRuleRelationsDo!=null) {
            FreeMarkerTemplateRulesDo freeMarkerTemplateRulesDo = freeMarkerTemplateRulesDao.selectByRuleId(templateRuleRelationsDo.getRuleId());
//            throw new IllegalArgumentException("The rule already exists in the template");
            map.put("ruleName", freeMarkerTemplateRulesDo.getName());
            return map;
        }
        // 获取插入后数据的ID
        Long ruleId = dto.getId();
        if(ruleId==null)
        {
            LambdaQueryWrapper<FreeMarkerTemplateRulesDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FreeMarkerTemplateRulesDo::getName, req.getName())
                            .eq(FreeMarkerTemplateRulesDo::getValue, req.getValue());

            FreeMarkerTemplateRulesDo freeMarkerTemplateRulesDo = freeMarkerTemplateRulesDao.selectOne(wrapper);
            if(freeMarkerTemplateRulesDo!=null)
            {
                ruleId=freeMarkerTemplateRulesDo.getId();
            }
        }
        // 插入关联关系
        TemplateRuleRelationsDo templateRuleRelationsDo2 = new TemplateRuleRelationsDo();
        templateRuleRelationsDo2.setTemplateId(templateId);
        templateRuleRelationsDo2.setRuleId(ruleId);
        templateRuleRelationsDao.insert(templateRuleRelationsDo2);
        return map;
    }

    private Long handlerRules(FreeMarkerTemplateRulesReq req, Long userId) {
        // 查询规则是否存在
        FreeMarkerTemplateRulesDo freeMarkerTemplateRulesDo = freeMarkerTemplateRulesDao.selectOne(
                new LambdaQueryWrapper<FreeMarkerTemplateRulesDo>()
                        .eq(FreeMarkerTemplateRulesDo::getName, req.getName())
                        .eq(FreeMarkerTemplateRulesDo::getValue, req.getValue())
        );
        Long ruleId=0L;
        if (freeMarkerTemplateRulesDo != null) {
            ruleId = freeMarkerTemplateRulesDo.getId();
            return ruleId;
        }
        return 0L;
    }


    @Override
    public void deleteRule(FreeMarkerTemplateDeleteRulesReq req) {
        Long templateId = req.getTemplateId();
        Long templateRuleId = req.getTemplateRuleId();
        LambdaQueryWrapper<TemplateRuleRelationsDo> wrapper = new LambdaQueryWrapper<>();
        //如果不为空才比较
        if (templateRuleId != null) {
            wrapper.eq(TemplateRuleRelationsDo::getRuleId, templateRuleId);
    }
        if(templateId != null)
        {
            wrapper.eq(TemplateRuleRelationsDo::getTemplateId, templateId);
        }
        if (templateRuleId != null && templateId != null) {
            templateRuleRelationsDao.delete(wrapper);
        }
        }

    @Override
    public  List<FreeMarkerTemplatePlaceHolderDo> placeHolderList() {
        List<FreeMarkerTemplatePlaceHolderDo> freeMarkerTemplatePlaceHolderDos = freeMarkerTemplatePlaceHolderDao.selectType(0L);
       return freeMarkerTemplatePlaceHolderDos;
    }

    /**
     * 获取当前时间并格式化为年月日时分秒
     * @return 格式化后的时间字符串
     */
    private String getCurrentFormattedDateTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }


    private IPage<FreeMarkerTemplateDo> pageInit(Map<String, String> map) {
        IPage<FreeMarkerTemplateDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }


    private QueryWrapper<FreeMarkerTemplateDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FreeMarkerTemplateDo> wrapper = new QueryWrapper<>();


        if (StringUtils.isNotBlank(map.get("name"))) {
            wrapper.like("name", map.get("name"));
        }

        return wrapper;
    }


}
